<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../view-app.html">
<link rel="import" href="../style/shared-styles.html">
<script src="../utilizes/formatDate.js"></script>
<dom-module id="view-dashboard-overview">
  <template>
    <style include="shared-styles app-grid-style">
      :host {
        margin: 10px;
        display: block;
      }

      .number {
        font-size: 7rem;
        text-align: center;
        margin-top: 20px;
      }

      .status {
        font-size: 4rem;
        text-align: center;
      }

      .frame {
        margin: 10px;
      }

      .app-grid {
        margin: 0;
      }

      .main-card {
        margin-top: 20px;
      }

      .btn {
        width: 250px;
      }

      .new-user {
        margin: 70px 0 10px 0;
      }

      .warn-blink {
        animation: blinker 1s linear infinite;
      }

      @keyframes blinker {
        50% {
          border: 1px solid #F44336;
        }
      }

      @media (min-width: 360px) and (max-width: 768px) {
        :host {
          --app-grid-columns: 1;
        }
        .number {
          font-size: 6rem;
        }
      }

      @media (min-width: 769px) and (max-width: 1024px) {
        :host {
          --app-grid-columns: 1;
        }
        .number {
          font-size: 6rem;
        }
      }

      @media (min-width: 1025px) and (max-width: 1200px) {
        :host {
          --app-grid-columns: 2;
        }
        .number {
          font-size: 6rem;
        }
      }

      @media (min-width: 1201px) {
        :host {
          --app-grid-columns: 3;
        }
      }
    </style>
    <firebase-auth app-name="smart-mes" id="auth" user="{{user}}"></firebase-auth>
    <firebase-document app-name="smart-mes" id="userData" path="/user/[[user.uid]]" data="{{k}}"></firebase-document>
    <firebase-query app-name="smart-mes" id="orderQuery" path="/data/[[k.key]]/orderData" data="{{orderData}}"></firebase-query>
    <firebase-query app-name="smart-mes" id="machineQuery" path="/data/[[k.key]]/factoryData/machine" data="{{machineData}}"></firebase-query>
    <firebase-query app-name="smart-mes" id="stationQuery" path="/data/[[k.key]]/factoryData/station" data="{{stationData}}"></firebase-query>
    <firebase-document app-name="smart-mes" id="factorySchedule" path="/data/[[k.key]]/factoryData/schedule" data="{{factorySchedule}}"></firebase-document>
    <firebase-document app-name="smart-mes" id="factoryOperation" path="/data/[[k.key]]/factoryData/operation" data="{{factoryOperation}}"></firebase-document>
    <firebase-document app-name="smart-mes" id="factoryPerformance" path="/data/[[k.key]]/factoryData/performance" data="{{factoryPerformance}}"></firebase-document>
    <firebase-document app-name="smart-mes" id="productionPerformance" path="/data/[[k.key]]/performanceData" data="{{productionPerformance}}"></firebase-document>
    <app-localstorage-document key="app-lang" data="{{language}}"></app-localstorage-document>
    <div class="card main-card">
      <ul class="app-grid">
        <template is="dom-if" if="[[isInitSetup(k.setup)]]">
          <li>
            <div class="frame warn-blink">
              <h1 class="title new-user">Are you new user?</h1>
              <p class="center">Please setup your factory before using.</p>
              <div class="center">
                <a name="setup" role="link" href="app/setup" rel="setup" tabindex="-1" title="Setup factory">
                  <paper-button class="btn">Setup your factory</paper-button>
                </a>
              </div>
            </div>
          </li>
        </template>
        <li>
          <div class="frame">
            <h1 class="title">{{localize('waiting-order')}}</h1>
            <h1 class="number">[[waitOrderCount]]</h1>
          </div>
        </li>
        <li>
          <div class="frame">
            <h1 class="title">{{localize('work-in-progress')}}</h1>
            <h1 class="number">[[wipOrderCount]]</h1>
          </div>
        </li>
        <li>
          <div class="frame">
            <h1 class="title">{{localize('completed-order')}}</h1>
            <h1 class="number">[[doneOrderCount]]</h1>
          </div>
        </li>

        <li>
          <div class="frame">
            <h1 class="title">{{localize('average-oee')}}</h1>
            <h1 class="number">[[productionPerformance.oee]] %</h1>
          </div>
        </li>
        <li>
          <div class="frame">
            <h1 class="title">{{localize('working-machines')}}</h1>
            <h1 class="number">[[machineData.length]]</h1>
          </div>
        </li>
        <li>
          <div class="frame">
            <h1 class="title">{{localize('working-stations')}}</h1>
            <h1 class="number">[[stationData.length]]</h1>
          </div>
        </li>
        <li>
          <div class="frame">
            <h1 class="title">{{localize('next-reschedule')}}</h1>
            <h1 class="number" style="font-size: 2.76rem;">[[getNextInterval(factorySchedule.start_interval, factorySchedule.interval)]]</h1>
          </div>
        </li>
        <li>
          <div class="frame">
            <h1 class="title">{{localize('reschedule-interval')}}</h1>
            <h1 class="number">[[factorySchedule.interval]]</h1>
          </div>
        </li>
        <li>
          <div class="frame">
            <h1 class="title">{{localize('operation-time-left')}}</h1>
            <h1 class="number" style="font-size: 2.76rem;">[[remainOpTime]]</h1>
          </div>
        </li>
      </ul>
    </div>
  </template>
  <script>
    /**
     * @ViewDashboardOverview
     * @polymer 
     * @extends {Polymer.Element}
     */
    class ViewDashboardOverview extends Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior],
      Polymer.Element) {
      static get is() {
        return 'view-dashboard-overview';
      }

      static get properties() {
        return {
          language: String,
          orderData: Object,
          machineData: Object,
          stationData: Object,
          factorySchedule: Object,
          factoryOperation: Object,
          factoryPerformance: Object,
          productionPerformance: Object,
          waitOrderCount: Number,
          doneOrderCount: Number,
          wipOrderCount: Number,
          remainOpTime: String,
          nextInterval: String,
          isInitial: Boolean,
          k: Object
        }
      }

      static get observers() {
        return [
          'getWaitOrder(orderData)',
          'getDoneOrder(orderData)',
          'getWIPOrder(orderData)',
          'getRemainOpTime(factoryOperation.op_end, factoryOperation.op_start, factoryOperation.op_day)',
          'getNextInterval(factorySchedule.start_interval, factorySchedule.interval)'
        ]
      }

      constructor() {
        super();
        this.isInitial = false;
      }

      connectedCallback() {
        super.connectedCallback()
        this.loadResources(this.resolveUrl('../../data/locales.json'))
      }

      isInitSetup(setup) {
        return !setup || false;
      }

      getNextInterval(last_timestamp, interval) {
        if (!last_timestamp || !interval) return 0
        const current = Math.floor(Date.now() / 1000)
        const diff = (current - last_timestamp)
        const range = (interval * 24 * 60 * 60) // convert day to seconds
        if (diff <= range) { // if diff still less than the day interval
          let nextIntervalTimeStamp = (last_timestamp * 1000) + (range * 1000)
          return dateFromTimeStamp(nextIntervalTimeStamp)
        } else { // else if diff exceed the day interval then set new start interval 
          this.set('factorySchedule.start_interval', current)
          let nextIntervalTimeStamp = (current * 1000) + (range * 1000)
          return dateFromTimeStamp(nextIntervalTimeStamp)
        }
      }

      getRemainOpTime(end, start, opday) {
        if (!end || !start || !opday) return this.localize('no-operation-day');
        const opdayArr = opday.split(",");
        const date = new Date();
        let dateText;

        switch (date.getDay()) {
          case 0:
            dateText = "sun";
            break;
          case 1:
            dateText = "mon";
            break;
          case 2:
            dateText = "tue";
            break;
          case 3:
            dateText = "wed";
            break;
          case 4:
            dateText = "thu";
            break;
          case 5:
            dateText = "fri";
            break;
          case 5:
            dateText = "sun";
            break;
          default:
            dateText = "N/A";
        }
        const current_hour = date.getHours();
        const current_minute = date.getMinutes();
        const current = current_hour + "." + current_minute;
        const endtime = end.replace(/\:/g, '.');
        const starttime = start.replace(/\:/g, '.');
        const timeleft = endtime - parseFloat(current);
        if (opday.includes(dateText)) {
          if (parseFloat(current) < starttime || parseFloat(current) > endtime) {
            this.remainOpTime = this.localize('end-of-shift');
          } else {
            this.remainOpTime = timeleft.toFixed(2) + " " + this.localize('hrs');
          }
        } else {
          this.remainOpTime = this.localize('day-off')
        }
      }

      getWaitOrder(orderData) {
        if (!orderData) return 0;
        if (orderData.length > 0) {
          const query = this.$.orderQuery.ref;
          query.orderByChild("order_status").equalTo("waiting").on("value", (snapshot) => {
            this.set('waitOrderCount', snapshot.numChildren());
          });
        } else {
          this.set('waitOrderCount', 0);
        }
      }

      getDoneOrder(orderData) {
        if (!orderData) return 0;
        if (orderData.length > 0) {
          const query = this.$.orderQuery.ref;
          query.orderByChild("order_status").equalTo("done").on("value", (snapshot) => {
            this.set('doneOrderCount', snapshot.numChildren());
          });
        } else {
          this.set('doneOrderCount', 0);
        }
      }

      getWIPOrder(orderData) {
        if (!orderData) return 0;
        if (orderData.length > 0) {
          const query = this.$.orderQuery.ref;
          query.orderByChild("order_status").equalTo("wip").on("value", (snapshot) => {
            this.set('wipOrderCount', snapshot.numChildren());
          });
        } else {
          this.set('wipOrderCount', 0);
        }
      }
    }
    customElements.define(ViewDashboardOverview.is, ViewDashboardOverview);
  </script>
</dom-module>